package com.example.yls.demoa;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by yls on 2018/9/25.
 */

public class MyAdapter extends BaseAdapter{
    private ArrayList<Student> studentArrayList;
    private Context context;

    public MyAdapter(Context context,ArrayList<Student> studentArrayList){
        this.context=context;
        this.studentArrayList=studentArrayList;
    }

    @Override
    public int getCount() {
        return studentArrayList.size(); //获取数量
    }

    @Override
    public Object getItem(int i) {
        return studentArrayList.get(i); //获取学生
    }

    @Override
    public long getItemId(int i) {
        return i; //获取位置
    }

    int count=0;
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Log.e("MyAdapter","getview"+i+"count="+count);

        //优化1 getview优化 view复用 先判断非空
        //先判断view是不是空，非空可以复用，不需要重新构建，节省内存
        if(view==null){
            count++;
            LayoutInflater layoutInflater=LayoutInflater.from((context));
            view = layoutInflater.inflate(R.layout.my_list_item,
                    viewGroup,false);

            //优化2 使用ViewHolder减少findView的次数，提高效率
            StuViewHolder holder=new StuViewHolder();
            holder.headImg=view.findViewById(R.id.headView);
            holder.ageView=view.findViewById(R.id.ageView);
            holder.nameView=view.findViewById(R.id.nameView);

            view.setTag(holder);
        }

        Student stu=studentArrayList.get(i);
        StuViewHolder holder=(StuViewHolder) view.getTag();
        holder.headImg.setImageResource(stu.getImgid());
        holder.nameView.setText(stu.getName());
        holder.ageView.setText(String.valueOf(stu.getAge()));

        return view;
    }
}
